//
//  CurrentUser.m
//  QuickView
//
//  Created by Liao on 13-11-20.
//  Copyright (c) 2013年 LCheng. All rights reserved.
//

#import "CurrentUser.h"
#import "WeiboApiClient.h"
#import "ApiConfig.h"

@interface CurrentUser ()

+ (CurrentUser *)nobody;
- (id)initWithDictionary:(NSDictionary *)dic;

@end


@implementation CurrentUser

@synthesize uid = _uid;
@synthesize name = _name;
@synthesize avatar_url = _avatar_url;
@synthesize token = _token;
@synthesize isLogin = _isLogin;

+ (CurrentUser *)SharedCurrentUser
{
    static CurrentUser *_sharedCuser = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSDictionary *userInfo = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_CURRENT_USER];
        if (userInfo) {
            _sharedCuser = [[CurrentUser alloc] initWithDictionary:userInfo];
        } else {
            _sharedCuser = [CurrentUser nobody];
        }
        
    });
    return _sharedCuser;
}

+ (CurrentUser *)nobody
{
    CurrentUser *user = [[CurrentUser alloc] init];
    user.uid = @"";
    user.name = @"";
    user.avatar_url = @"";
    user.token = @"";
    user.isLogin = NO;
    return user;
}

- (id)initWithDictionary:(NSDictionary *)dic
{
    self = [super init];
    if (self) {
        _uid = [dic valueForKey:@"uid"];
        _name = [dic valueForKey:@"name"];
        _avatar_url = [dic valueForKey:@"avatar_url"];
        _token = [dic valueForKey:@"token"];
        if (![_uid isEqualToString:@""]) {
            _isLogin = YES;
        } else {
            _isLogin = NO;
        }
    }
    return self;
}

#pragma mark -- about the login
+ (CurrentUser *)GetUserWithCheckLogin
{
    CurrentUser *cuser = [self SharedCurrentUser];
    if (![cuser.uid isEqualToString:@""]) {
        NSString *token = cuser.token;
        NSDictionary *param = @{@"access_token":token};
        [[WeiboApiClient sharedClient] GET:WEIBO_API_GET_UID parameters:param success:^(NSURLSessionDataTask * __unused task, id JSON) {
                if ([JSON valueForKey:@"uid"]) {
                    NSLog(@"check ok, token: %@", cuser.token);
                    cuser.isLogin = YES;
                } else {
                    NSLog(@"try logout");
                    [self tryLogout];
                };
            }
            failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
                [self tryLogout];
                NSLog(@"%@", error);
            }];
    }
    return cuser;
}

+ (void)tryLogin
{
    if (![self SharedCurrentUser].isLogin) {
        WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        request.redirectURI = kRedirectURI;
        request.scope = @"all";
        request.userInfo = @{};
        [WeiboSDK sendRequest:request];
    }
}

+ (void)Login:(NSString *)uid Token:(NSString *)token
{
    //从open接口获取
    NSDictionary *params = @{@"source":kAppKey, @"access_token":token, @"uid":uid};
    [[WeiboApiClient sharedClient] GET:WEIBO_API_USER_SHOW parameters:params success:^(NSURLSessionDataTask * __unused task, id JSON) {
            if ([JSON valueForKey:@"id"]) {
                CurrentUser *user = [self SharedCurrentUser];
                user.uid = [JSON valueForKey:@"idstr"];
                user.name = [JSON valueForKey:@"screen_name"];
                user.avatar_url = [JSON valueForKey:@"profile_image_url"];
                user.token = token;
                user.isLogin = YES;
                [self Save:user];
                //[[NSNotificationCenter defaultCenter] postNotificationName:QV_DID_LOGIN_NOTIFICATION object:self];
            } else {
                //todo  handle error
                //NSLog(@"response error: %@", JSON);
            }
    
        } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
            //todo  handle error;
            //NSLog(@"request error: %@", error);
        }];
}

+ (void)tryLogout
{
    CurrentUser *cuser = [self SharedCurrentUser];
    NSString *token = cuser.token;
    cuser.uid = @"";
    cuser.token = @"";
    cuser.name = @"";
    cuser.avatar_url = @"";
    cuser.isLogin = NO;
    [self Save:cuser];
    [WeiboSDK logOutWithToken:token delegate:(id<WBHttpRequestDelegate>)self withTag:@""];
}

+ (NSString *)GetToken
{
    return [self GetUserWithCheckLogin].token;
}

+ (void)Save:(CurrentUser *)user
{
    NSDictionary *info = @{@"uid":user.uid,
                           @"name":user.name,
                           @"avatar_url":user.avatar_url,
                           @"token":user.token};
    [[NSUserDefaults standardUserDefaults] setObject:info forKey:KEY_CURRENT_USER];
}


- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    ;
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    ;
}


@end
